package com.my.serviceimpl;

import com.my.bean.File;
import com.my.bean.User;
import com.my.mapper.FileMapper;
import com.my.service.FileService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.my.util.FileUpload;
import com.my.util.SessionUtil;
import org.apache.commons.fileupload.FileUploadBase;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.FileNotFoundException;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 上传文件 服务实现类
 * </p>
 *
 * @author 张子艺
 * @since 2018-10-08
 */
@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, File> implements FileService {

    @Override
    public boolean uploadFile(MultipartFile multipartFile, Long RelactionId, HttpSession session) {
        try {
            //获取上传完成后 返回的路径

            String url= FileUpload.fileUpload(multipartFile);


            com.my.bean.File file=new com.my.bean.File();
            file.setUrl(url);
            file.setCreateTime(new Date().getTime());
            file.setRelationId(RelactionId);
            //获取文件名
            file.setFileName(multipartFile.getOriginalFilename());
            Long areaid=((User)session.getAttribute("user")).getAreaId();
            file.setAreaid(areaid);
            if(this.insert(file)){
                return  true;
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return  false;
    }

    @Override
    public boolean deleteFile(Long fileId)   {
        Map map=new HashMap<>();
        map.put("id",fileId);
        List<File> files= this.selectByMap(map);
            //删除文件
            if(FileUpload.deleteFile(files.get(0).getUrl())){
                if( this.deleteById(fileId)){
                    return true;
                };
            };
        return false;
    }




}
